<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { notificationApi } from '@/api/modules/notification'
import { NotificationVO } from '@/types/notification'
import { Table, Button, message, Modal } from 'ant-design-vue'
import dayjs from 'dayjs'
import { useUserStore } from '@/stores/user' // 引入用户状态管理

const loading = ref(false)
const notifications = ref<NotificationVO[]>([])
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true, // 显示页码选择器
  showTotal: (total: number) => `共 ${total} 条`, // 显示总数
  pageSizeOptions: ['10', '20', '30', '50'],
  // 自定义页码选项的文本
  buildOptionText: (opt: { value: number }) => {
    return `${opt.value} 条/页`
  }
})
const selectedNotification = ref<NotificationVO | null>(null)
const modalVisible = ref(false) // 新增控制弹窗显示的变量

const userStore = useUserStore()

// 获取通知列表
const fetchNotifications = async (page = pagination.value.current, pageSize = pagination.value.pageSize) => {
  loading.value = true
  try {
    const data = await notificationApi.getNotifications({}, page - 1, pageSize)
    console.log('Fetched notifications:', data) // 调试信息
    notifications.value = data.content // 确保正确赋值
    pagination.value.total = data.totalElements // 确保正确赋值
    pagination.value.current = page
    pagination.value.pageSize = pageSize
  } catch (error) {
    console.error('获取通知失败:', error)
    message.error(error || '获取通知失败')
  } finally {
    loading.value = false
  }
}

// 处理分页变化
const handleTableChange = (pag: any) => {
  fetchNotifications(pag.current, pag.pageSize)
}

// 标记为已读
const handleMarkAsRead = async (id: number) => {
  try {
    await notificationApi.markAsRead(id)
    message.success('已标记为已读')
    fetchNotifications() // 刷新通知列表
  } catch (error) {
    message.error(error||'标记为已读失败')
  }
}

// 格式化时间
const formatTime = (time: string) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

// 查看通知详情
const handleViewDetails = async (notification: NotificationVO) => {
  selectedNotification.value = notification
  modalVisible.value = true // 显示弹窗
  let userInfo = await userStore.getUserInfo();
  console.log('userInfo.userType',userInfo)
  // 如果不是管理员且通知未读，则标记为已读
  if (userInfo.userType!==1 && !notification.isRead) {
    await handleMarkAsRead(notification.id)
  }
}

// 关闭弹窗
const handleCloseModal = () => {
  modalVisible.value = false
  selectedNotification.value = null
}

// 页面加载时获取通知
onMounted(() => {
  fetchNotifications()
})

// 添加样式类判断方法
const getNotificationClass = (notification: NotificationVO) => {
  return {
    'notification-unread': !notification.read,
    'notification-read': notification.read
  }
}

// 删除通知
const handleDelete = async (id: number) => {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除这条通知吗？',
    okText: '确定',
    cancelText: '取消',
    okType: 'danger',
    async onOk() {
      try {
        await notificationApi.deleteNotification(id)
        message.success('删除成功')
        // 刷新通知列表
        fetchNotifications(pagination.value.current, pagination.value.pageSize)
      } catch (error) {
        if (error instanceof Error) {
          message.error(error||'删除失败：' + error.message)
        }
      }
    }
  })
}
</script>

<template>
  <div>
    <h1>通知公告</h1>
    <Table
      :data-source="notifications"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
      row-key="id"
    >
      <a-table-column title="标题" dataIndex="title" align="center">
        <template #default="{ record }">
          <span 
            :class="getNotificationClass(record)"
            @click="handleViewDetails(record)"
          >
            {{ record.title }}
            <badge v-if="!record.read" color="#f50" dot />
          </span>
        </template>
      </a-table-column>
      <a-table-column title="内容" dataIndex="content" align="center">
      </a-table-column>
      <a-table-column title="创建时间" dataIndex="createTime" align="center">
        <template #default="{ record }">
          {{ formatTime(record.createTime) }}
        </template>
      </a-table-column>
      <a-table-column title="操作" width="200px" align="center">
        <template #default="{ record }">
          <Button 
            @click="handleDelete(record.id)"
            type="link"
            danger
            size="small"
          >
            删除
          </Button>
        </template>
      </a-table-column>
    </Table>

    <!-- 修改通知详情弹窗 -->
    <Modal
      v-model:visible="modalVisible"
      :maskClosable="false"
      title="通知详情"
      @cancel="handleCloseModal"
      :footer="null"
      width="600px"
    >
      <div v-if="selectedNotification" class="notification-detail">
        <h2 class="notification-title">{{ selectedNotification.title }}</h2>
        <div class="notification-meta">
          <span>创建时间：{{ formatTime(selectedNotification.createTime) }}</span>
        </div>
        <div class="notification-content">
          {{ selectedNotification.content }}
        </div>
      </div>
    </Modal>
  </div>
</template>

<style scoped>
.notification-unread {
  font-weight: bold;
  color: #1890ff; /* 蓝色 */
}

.notification-read {
  color: rgba(0, 0, 0, 0.65); /* 灰色 */
}

/* 添加鼠标悬停效果 */
.notification-unread:hover,
.notification-read:hover {
  cursor: pointer;
  text-decoration: underline;
}

/* 表格行样式 */
:deep(.ant-table-row) {
  background-color: transparent;
  transition: background-color 0.3s;
}

:deep(.ant-table-row:hover) {
  background-color: #f5f5f5;
}

/* 未读消息行样式 */
:deep(.ant-table-row.unread) {
  background-color: #e6f7ff;
}

/* 按钮样式 */
.ant-btn {
  margin-right: 8px;
}

/* 徽标样式 */
.ant-badge {
  margin-left: 8px;
}

/* 详情弹窗样式 */
.notification-detail {
  padding: 16px;
}

.notification-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 16px;
  color: #1890ff;
}

.notification-meta {
  color: #666;
  margin-bottom: 16px;
  font-size: 14px;
}

.notification-content {
  font-size: 16px;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-all;
}

/* 内容省略号 */
.notification-content-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 300px;
}

/* 操作按钮样式 */
.ant-btn {
  margin-right: 8px;
}

/* 删除按钮悬停样式 */
.ant-btn-link.ant-btn-dangerous:hover {
  background-color: #fff1f0;
}
</style> 